<template>
  <div class="pageWrapper">
    <SearchBar class="form" @onSearch="handleSearch" @childFn="resetForm">
      <SearchBarItem label="清分日期：" :labelLg="8">
        <DatePicker
          type="daterange"
          ref="createDatePicker"
          split-panels
          transfer
          placeholder="起始时间"
          @on-change="createTime"
          :value="urlClearDate"
        ></DatePicker>
      </SearchBarItem>
    </SearchBar>
    <RemoteTable
      :namespace="namespace"
      :columns="columns"
      :showPageInfo="false"
      :isFixedHeader="true"
      :selected="exportData"
      @onSortChange="onSortChange"
      @onSelectionChange="getListChecked"
      ref="remoteTable"
    >
      <template #extra>
        <Authc permissions="trade:settlement:cmb">
          <Button type="primary" @click="exportExcel">导出</Button>
        </Authc>
      </template>

    </RemoteTable>
    <br />
    <Row>
      <Col span="12" offset="11">
        <Button type="primary" @click="loadMore" :disabled="isDisabledloadBtn"
          >加载更多</Button
        >
      </Col>
    </Row>
  </div>
</template>
<script>
import RemoteTable from '@/components/RemoteTable';
import SearchBar from '@/components/SearchBar';
import RemoteSelect from '@/components/RemoteSelect';
import { namespace } from '../Module/clearingCollectModule';
import Authc from '@/components/Authc';
import Tables from '@/components/tables';
import Action from './Action';
import config from '@/utils/config';
import util from '@/utils/util';
import appService from '@/utils/appService';

export default {
  name: 'clearingCollect',
  components: {
    RemoteTable,
    SearchBar,
    SearchBarItem: SearchBar.SearchBarItem,
    RemoteSelect,
    Authc,
    Action,
    Tables
  },
  data() {
    return {
      isShowDate: false,
      requireUrl: '',
      urlClearDate: [
        util.fun_date(-7),
        new Date().getFullYear() +
          '-' +
          (new Date().getMonth() + 1) +
          '-' +
          new Date().getDate()
      ],
      namespace: namespace,
      isClear: true,
      loading: true,
      modal1: false,
      dataModule: {}, //查询条件
      tableData: [],
      exportData: [] /** 存放导出的数据 **/,
      currentPage: 1 /** 用来控制加载更新 **/,
      isDisabledloadBtn: false /** 控制加载更多按钮 **/,
      columns: [
        {
          title: '平台日汇总',
          align: 'center',
          children: [
            {
              type: 'selection',
              align: 'center',
              minWidth: 55
            },
            {
              title: '序号',
              type: 'index',
              align: 'center',
              minWidth: 80
            },
            {
              title: '清分日期',
              key: 'clearDate',
              align: 'center',
              minWidth: 100
            },
            {
              title: '平台商户总数',
              key: 'merchantCount',
              align: 'center',
              minWidth: 120
            },
            {
              title: '平台子订单总数',
              key: 'subOrderCount',
              align: 'center',
              minWidth: 130
            },
            {
              title: '平台清分记账数',
              key: 'orderCount',
              align: 'center',
              minWidth: 130
            },
            {
              title: '平台清分总金额(元)',
              key: 'clearAmountCount',
              align: 'center',
              minWidth: 150,
              render: (h, params) => {
                let item = params.row.clearAmountCount / 100;
                return h('span', util.toMoney(item));
              }
            }
          ]
        },
        {
          title: '银行日汇总',
          key: 'gender',
          align: 'center',
          children: [
            {
              title: '银行商户总数',
              key: 'bank_merchant_count',
              align: 'center',
              minWidth: 120
            },
            {
              title: '银行子订单总数',
              key: 'bank_sub_order_count',
              align: 'center',
              minWidth: 130
            },
            {
              title: '银行清分记账数',
              key: 'bankOrderCount',
              align: 'center',
              minWidth: 130
            },
            {
              title: '银行清分总金额(元)',
              key: 'bankClearAmountCount',
              align: 'center',
              minWidth: 150,
              render: (h, params) => {
                let item = params.row.bankClearAmountCount / 100;
                return h('span', util.toMoney(item));
              }
            }
          ]
        },
        {
          title: '差异日汇总',
          key: 'gender',
          align: 'center',
          children: [
            {
              title: '差异商户数',
              key: 'diffMerchantCount',
              align: 'center',
              minWidth: 100
            },
            {
              title: '差异订单数',
              key: 'diffSubOrderCount',
              align: 'center',
              minWidth: 100
            },
            {
              title: '差异记账数',
              key: 'diffOrderCount',
              align: 'center',
              minWidth: 100
            },
            {
              title: '差异清分总金额(元)',
              key: 'diffClearAmountCount',
              align: 'center',
              minWidth: 150,
              render: (h, params) => {
                let item = params.row.diffClearAmountCount / 100;
                return h('span', util.toMoney(item));
              }
            },
            {
              title: '对账日期',
              key: 'billDate',
              align: 'center',
              minWidth: 180
            },
            {
              title: '操作',
              key: 'action',
              align: 'center',
              permissions: ['trade:settlement:cmb'],
              minWidth: 200,
              render: function(h, data) {
                return h(Action, {
                  props: {
                    row: data.row,
                    isShowDiffBtn:
                      data.row.diffSubOrderCount == 0 ||
                      data.row.diffOrderCount == 0
                        ? false
                        : true
                  }
                });
              }
            }
          ]
        }
      ]
    };
  },
  created() {
    /** 重置请求参数, 解决搜索之后，请求参数没有清空的问题 **/
    this.$store.commit(`${namespace}/reviseQuery`);
  },
  mounted() {
    setTimeout(() => {
      this.loading = false;
    }, 1000);
  },
  methods: {
    exportExcel() {
      if (this.exportData.length == 0) {
        this.$Message.error({
          content: '请选择导出的数据'
        });
        return;
      } else {
        this.exportData.forEach(e => {
          // if (e.clearAmountCount || e.bankClearAmountCount || e.diffClearAmountCount) {
          e.merchantCount = e.merchantCount || '';
          e.subOrderCount = e.subOrderCount || `\t0`;
          e.orderCount = e.orderCount || `\t0`;
          e.clearAmountCount = e.clearAmountCount / 100 || `\t0`;
          e.bank_merchant_count = e.bank_merchant_count || `\t0`;
          e.bank_sub_order_count = e.bank_sub_order_count || `\t0`;
          e.bankOrderCount = e.bankOrderCount || `\t0`;
          e.bankClearAmountCount = e.bankClearAmountCount / 100 || `\t0`;
          e.diffMerchantCount = e.diffMerchantCount || `\t0`;
          e.diffSubOrderCount = e.diffSubOrderCount || `\t0`;
          e.diffOrderCount = e.diffOrderCount || `\t0`;
          e.diffClearAmountCount = e.diffClearAmountCount / 100 || `\t0`;
          e.billDate = e.billDate || `\t0`;
          // }
        });
      }

      /** 多表头处理 **/
      let exportColumn = this.handleMultiTableHeader(this.columns, false);

      /** 复制一份表头 **/
      let columnOne = {};
      exportColumn.forEach(item => {
        columnOne[item.key] = item.title;
      });

      /** 自定义导出表格第一行的表头，逗号表示隔开几个单元格 **/
      let tableTitle = {
        clearDate: `${this.columns[0].title},,,,,${this.columns[1].title},,,,${this.columns[2].title}`,
        merchantCount: '',
        subOrderCount: '',
        orderCount: '',
        clearAmountCount: '',
        bank_merchant_count: '',
        bank_sub_order_count: '',
        bankOrderCount: '',
        bankClearAmountCount: '',
        diffMerchantCount: '',
        diffSubOrderCount: '',
        diffOrderCount: '',
        diffClearAmountCount: '',
        billDate: ''
      };
      /** 复制一份导出数据 **/
      let copyTableData = JSON.parse(JSON.stringify(this.exportData));
      /** 把自定义的表头和复制出来的表头，添加到导出数据前面 **/
      copyTableData.unshift(tableTitle, columnOne);

      let tables = this.$refs.remoteTable.getTables();
      tables.exportCsv({
        filename: '清分汇总统计',
        columns: exportColumn,
        data: copyTableData.map(item => {
          return {
            clearDate: `\t${item.clearDate}`,
            merchantCount: `\t${item.merchantCount}`,
            subOrderCount: `\t${item.subOrderCount}`,
            orderCount: `\t${item.orderCount}`,
            clearAmountCount: `\t${item.clearAmountCount}`,
            bank_merchant_count: `\t${item.bank_merchant_count}`,
            bank_sub_order_count: `\t${item.bank_sub_order_count}`,
            bankOrderCount: `\t${item.bankOrderCount}`,
            bankClearAmountCount: `\t${item.bankClearAmountCount}`,
            diffMerchantCount: `\t${item.diffMerchantCount}`,
            diffSubOrderCount: `\t${item.diffSubOrderCount}`,
            diffOrderCount: `\t${item.diffOrderCount}`,
            diffClearAmountCount: `\t${item.diffClearAmountCount}`,
            billDate: `\t${item.billDate}`
          };
        }),
        noHeader: true
      });
    },
    handleSearch() {
      // this.currentPage = 1;
      let obj = {
        currentPage: 1,
        pageSize: 50
      };
      this.$store.dispatch(`${namespace}/query`, {
        ...this.dataModule,
        ...obj
      });
    },
    onSortChange(sort) {
      if (sort.order === 'normal') {
        this.queryParam.order = [];
      } else {
        this.queryParam.order = [sort.key + ' ' + sort.order];
      }
      this.handleSearch();
    },
    /** 加载更多 **/
    async loadMore() {
      if (!this.isShowDate) {
        this.dataModule = {
          startDate: util.fun_date(-7),
          endDate:
            new Date().getFullYear() +
            '-' +
            (new Date().getMonth() + 1) +
            '-' +
            new Date().getDate()
        };
      }
      try {
        this.isDisabledloadBtn = true; // 每次请求都禁止按钮点击
        let obj = {
          currentPage: ++this.currentPage,
          pageSize: 50
        };
        /** 因为不是翻页，所以重新写了一个列表的请求 **/
        let res = await this.$store.dispatch(`${namespace}/getMoreList`, {
          ...this.dataModule,
          ...obj
        });
        let listData = res.data.data.list;
        if (listData.length != 0) {
          /** 拿到数据，就拼接到 vuex 里面 **/
          this.$store.commit(`${namespace}/pushDataToList`, listData);
        } else {
          --this.currentPage;
          this.$Message.info({
            content: '没有更多数据了！'
          });
        }
        this.isDisabledloadBtn = false;
      } catch (error) {
        this.$Message.error({
          content: error
        });
      }
    },
    /** 列表选择 **/
    getListChecked(data) {
      this.exportData = data;
    },
    /** cy 处理多表头导出问题 **/
    handleMultiTableHeader(columns) {
      return columns
        .map(res => {
          if (res.hasOwnProperty('children')) {
            /** 通过 key 过滤掉 复选框和序号还有操作栏 **/
            return res.children.filter(item => {
              return item.key;
            });
          } else {
            return res;
          }
        })
        .flat();
    },
    // 清空事件；
    resetForm() {
      // 清空时间选择
      this.$refs['createDatePicker'].handleClear();
    },
    // 清分日期
    createTime(date, type) {
      this.isShowDate = true;
      this.dataModule.startDate = date ? date[0] : '';
      this.dataModule.endDate = date ? date[1] : '';
    }
  }
};
</script>
<style scoped></style>
